package com.gae.onlinestore.services;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gae.onlinestore.entity.EntityManagerFactory;
import com.gae.onlinestore.entity.Customer;
import com.google.gson.Gson;

public class CustomerServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;
	protected void processInsertAndSendMail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<html>");
		out.println("<head>");
		out.println("<title>Successful create account</title>");
		out.println("</head>");
		out.println("<body>");
			
			String mailTo = request.getParameter("tbEmail");
			String mailSubject = "Online Stationery Store::User Account Information";
			
			String password = request.getParameter("tbPassword");
			String fname = request.getParameter("tbFirstname");
			String lname = request.getParameter("tbLastname");
			String address = request.getParameter("tbAddrees");
			String city = request.getParameter("tbCity");
			String country = request.getParameter("tbCountry");
			String zipCode = request.getParameter("tbZipCode");
			String phone = request.getParameter("tbPhone");
			
			StringBuilder mailBody = new StringBuilder();
			mailBody.append("Hi, "+fname+ " "+lname+"\n\n");
			mailBody.append("Thank you for your registration on Online Stationery Store. \n");
			mailBody.append("Please use the information below to login to http://teststationarystore.appspot.com/ \n");
			mailBody.append("\nUsername : "+mailTo +"\n");
			mailBody.append("Password : "+password+"\n");
			mailBody.append("\nCheers,\n");
			mailBody.append("Online Stationery Store Team");
			
			Properties props = new Properties();
			Session session = Session.getDefaultInstance(props, null);
			
			Customer customer = new Customer(fname,lname,mailTo,password,address,city,country,zipCode,phone);
			
			EntityManager em = EntityManagerFactory.get().createEntityManager();
			try {
	            em.persist(customer);
	            out.println("Your account has been created!!<br />");
	            
				try {
					Message msg = new MimeMessage(session);
					msg.setFrom(new InternetAddress("thanyaammyy@gmail.com","<No-Reply>Online-Shopping Team"));
//					msg.addRecipient(Message.RecipientType.BCC,
//							new InternetAddress("tamujinz@gmail.com"));
//					msg.addRecipient(Message.RecipientType.BCC,
//							new InternetAddress("doctor.aong@gmail.com"));
					msg.addRecipient(Message.RecipientType.TO,
					new InternetAddress(mailTo));
					msg.setSubject(mailSubject);
					msg.setText(mailBody.toString());
					Transport.send(msg);
					
					out.println("Please see the account detail in your e-mail.");
				} catch (AddressException ex) {
					out.println("Invalid email address!!");
					out.println(ex);
					ex.printStackTrace();
				} catch (MessagingException ex) {
					out.println("Error while sending Email message");
					out.println(ex);
					ex.printStackTrace();
				}
			}catch (Exception ex) {
				out.println("Cannot create your account");
				out.println(ex);
				
	        }
	        finally {
	            em.close();
	            out.close();
	        }

			
		out.println("</body>");
		out.println("</html>");
		out.close();
	}
	
	protected void processSelect (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
		resp.setContentType("application/json; charset=utf-8");
		PrintWriter out = resp.getWriter();
		EntityManager em = EntityManagerFactory.get().createEntityManager();
		String mail = req.getParameter("tbEmail");
		String password = req.getParameter("tbPassword");
		Gson gson = new Gson();
		String strQuery = "SELECT o FROM Customer AS o where email= '"+mail+"' and password= '"+password+"'";
		try{
			Query query = em.createQuery(strQuery);
			@SuppressWarnings("unchecked")
			Customer results = (Customer) query.getResultList().get(0);
			if(query.getResultList().size() == 0){
				out.println(gson.toJson(null));
			}
			else{
				out.println(gson.toJson(results));
				Cookie c = new Cookie("User",gson.toJson(results));
				resp.addCookie(c);
			}
			
		} catch(Exception ex) {
            out.println(ex);
        } finally {
            em.close();
            out.close();
        }
	}
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		processSelect(request, response);
	}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
		processInsertAndSendMail(request, response);
	}
}
